#ifndef PAGEDQUERYWIDGET_H
#define PAGEDQUERYWIDGET_H

#include <QWidget>
#include <QMap>
#include <QVariant>
#include <QFile>
#include "configmanager.h"

class QTableView;
class QPushButton;
class QLabel;
class QLineEdit;
class QComboBox;
class QHBoxLayout;
class QVBoxLayout;
class FilterWidget;
class TableModel;

class PagedQueryWidget : public QWidget
{
    Q_OBJECT
public:
    explicit PagedQueryWidget(const QString &configPath, QWidget *parent = nullptr);

    void setData(const QVector<QMap<QString, QVariant>> &data, int totalCount);

    QMap<QString, QVariant> getFilterValues() const;

    void loadStyleSheet();

    // 获取当前排序字段
    QString getSortField() const { return m_sortField; }

    // 获取当前排序顺序
    Qt::SortOrder getSortOrder() const { return m_sortOrder; }

    // 获取当前页码
    int getCurrentPage() const { return m_currentPage; }

    // 获取当前页大小
    int getPageSize() const { return m_pageSize; }
signals:
    void pageChanged(int page, int pageSize);
    void filterChanged(const QMap<QString, QVariant> &filters);
    void sortChanged(const QString &field, Qt::SortOrder order);
    void cellClicked(int row, int column, const QString &field, const QVariant &value);

private slots:
    void onFilterApplied();
    void onHeaderClicked(int section);
    void onTableClicked(const QModelIndex &index);
    void onPageSizeChanged(int index);
    void onFirstPage();
    void onPrevPage();
    void onNextPage();
    void onLastPage();
    void onJumpToPage();
    void updatePaginationControls();

protected:
    void resizeEvent(QResizeEvent *event) override;

private:
    ConfigManager *m_configManager;
    FilterWidget *m_filterWidget;
    QTableView *m_tableView;
    TableModel *m_tableModel;

    // 分页控件
    QLabel *m_totalLabel;
    QPushButton *m_firstPageBtn;
    QPushButton *m_prevPageBtn;
    QLabel *m_pageInfoLabel;
    QPushButton *m_nextPageBtn;
    QPushButton *m_lastPageBtn;
    QLineEdit *m_jumpPageEdit;
    QPushButton *m_jumpPageBtn;
    QComboBox *m_pageSizeCombo;

    // 分页状态
    int m_currentPage;
    int m_pageSize;
    int m_totalCount;
    int m_totalPages;

    // 排序状态
    QString m_sortField;
    Qt::SortOrder m_sortOrder;

    void initUI();
    void initConnections();
    void calculatePageInfo();
    int calculateOptimalPageSize();
};

#endif // PAGEDQUERYWIDGET_H

